package cn.fiveinone;

import cn.fiveinone.setting.Setting;

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

/**
 * @Description
 * @auther Szper
 * @create 2019-10-24 14:12
 */
public class BaseService extends PoolExactor {
    final static void putBean (String TPYFWYM, boolean TPYRZDY, int TPYDK, String rmname, BaseActive paobj) {
        if (TPYFWYM != null) {
            System.setProperty("java.rmi.server.hostname", TPYFWYM);
        }
        if (TPYRZDY) {
            System.setProperty("java.rmi.server.logCalls", "true");
        }
        try {
            LocateRegistry.getRegistry(TPYDK).list();
        } catch (Exception ex) {
            try {
                UnicastRemoteObject.exportObject(paobj, 0);
                Registry registry = LocateRegistry.createRegistry(TPYDK);
                registry.rebind(rmname, paobj);
            } catch (Exception e) {
                System.out.println("[BaseService]" + "[putBean]" + e);
            }
        }
    }
    final static void putBean (String host, boolean TPYRZDY, int port, String rmname, BaseActive paobj, String cb, String pl, SecurityManager sm) {
        setSecurity(cb, pl, sm);
        putBean(host, TPYRZDY, port, rmname, paobj);
    }
    final static BaseActive getBean (String host, int port, String rmname) throws RemoteException {
        try {
            if (Setting.getTMOT() > 0L) {
                System.setProperty("sun.rmi.transport.tcp.responseTimeout", Setting.getTMOT() + "");
            }
            return (BaseActive) Naming.lookup(Setting.getProtocolInfo(host, port, rmname));
        } catch (Exception e) {
            if(e instanceof RemoteException)
                throw (RemoteException)e;
            else{
                //e.printStackTrace();
                System.out.println("[BaseService]" + "[getBean]" + "[Error Exception:]" + e);
            }
        }
        return null;
    }

    /**
     * 安全管理器
     * @param cb
     * @param pl
     * @param sm
     */
    private static void setSecurity(String cb, String pl, SecurityManager sm){
        if(cb!=null&&pl!=null){
            System.setProperty("java.rmi.server.codebase",cb);
            System.setProperty("java.security.policy",pl);
            if(System.getSecurityManager()==null&&sm!=null){
                System.setSecurityManager(sm);//ParkManager()
            }
        }
    }
}
